var express = require('express');
var router = express.Router();
const Blog = require('../connet/mongod')
// 查询
router.post('/', async (req, res)=>{
  try {
    const page = req.body.page || 1
    const pageSize = req.body.pageSize || 10
    const count = await Blog.Article.find().countDocuments()
    const data = await Blog.Article.find().limit(pageSize).skip((page-1)*pageSize)
    res.status(200).send({data, isok: true, count})
    console.log(data, 'data')
  } catch (error) {
    console.log(error, '错误');
  }
});
//根据title查询 包含title的都会被查询到
router.post('/searchbytitle', async (req, res)=>{
  try {
    const page = req.body.page || 1
    const pageSize = req.body.pageSize || 10
    const data = await Blog.Article.find({title:{$regex:req.body.title}}).limit(pageSize).skip((page-1)*pageSize)
    // const data = await Blog.Article.find({title:{$regex:req.body.title}})
    res.status(200).send(data, {isok: true})
  } catch (error) {
    console.log(error, '错误');
  }
});
//根据type查询
router.post('/searchbytype', async (req, res)=>{
  try {
    const page = req.body.page || 1
    const pageSize = req.body.pageSize || 10
    const count = await Blog.Article.find({type:req.body.type}).countDocuments()
    const data = await Blog.Article.find({type:req.body.type}).limit(pageSize).skip((page-1)*pageSize)
    // const data = await Blog.Article.find({type:req.body.type})
    console.log(data, 'data', req.body);
    res.status(200).send({data, isok: true , count})
  } catch (error) {
    console.log(error, '错误');
  }
});
//根据id查询
router.post('/searchbyid', async (req, res)=>{
  try {
    console.log(req.body._id, 'req.body._id');
    const data = await Blog.Article.find({_id:req.body._id})
    res.status(200).send({data, isok: true})
  } catch (error) {
    console.log(error, '错误');
  }
});
// 新增
router.post('/create', async (req, res)=>{
  const insertdata = req.body
  console.log(req.body, '参数');
  const stringcount = insertdata.content.length;
  console.log(stringcount, '字符串长度');
  // 使用正则表达式匹配第一个 <img> 标签
  const imgTag = insertdata.content.match(/<img[^>]*src=["']?([^"'>]+)["']?[^>]*>/i);
  if (imgTag) {
    const pic = imgTag[1];
    console.log('src 属性的值', pic);
  } else {
    console.log('没有找到 <img> 标签或 src 属性');
  }
  const insertdatas = {
    ...insertdata,
    stringcount,
    pic: imgTag ? imgTag[1] : ''
  }
  const data = await Blog.Article.create(insertdatas)
  res.status(200).send({data,isok:true})
})
// 删除
router.post('/delete', async function(req, res){
    const _id = req.body._id
    const data = await Blog.Article.deleteOne({_id});
    res.status(200).send({data,isok:true})
  })
// 修改
router.post('/update', async function(req, res){
    const query = req.body
    const data = await Blog.Article.updateOne({_id:query.id}, query);
    res.status(200).send({data,isok:true})
  })

module.exports = router;
